<template>
	<view class="chatInterface">
		<view class="scroll-view">
			<view class="all-history-loaded">{{ allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息' }}</view>
			<!--已经收到的消息-->
			<view v-for="(message, index) in messages" :key="message.messageId">
				<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
				<view class="time-lag">{{ renderMessageDate(message, index) }}</view>
				<view class="message-item" :class="{ self: message.senderId == (currentUser && currentUser.uuid) }">
					<view class="avatar" v-if="message.senderId != (currentUser && currentUser.uuid)"><image :src="friend.avatar"></image></view>
					<view class="avatar" v-else><image :src="currentUser.avatar"></image></view>
					<view class="content">
						<b class="pending" v-if="message.status == 'sending'"></b>
						<b class="send-fail" v-if="message.status == 'fail'"></b>
						<view v-if="message.type == 'text'">
							<span class="text-content">{{ message.payload.text }}</span>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="action-box">
			<view class="action-top">
				<view class="message-input">
					<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
					<input type="text" maxlength="700" placeholder="发送消息" v-model="content" />
				</view>
				<span class="send-message-btn" @click="sendTextMessage">发送</span>
			</view>
		</view>
	</view>
</template>

<script>
import restApi from '@/utils/goeasy/restapi';
export default {
	name: 'privateChat',
	data() {
		return {
			//聊天文本框
			content: '',
			friend: null,
			currentUser: null,
			//已经接收到的消息
			messages: [],
			//已经加载完所有历史消息
			allHistoryLoaded: false
		};
	},
	onReady() {
		// https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle
		// uni.setNavigationBarTitle({
		// 	title: this.friend.name
		// });
	},
	onShow() {},
	onLoad(options) {
		this.init(options);
	},
	onPullDownRefresh(e) {
		this.loadMoreHistoryMessage();
	},
	onUnload() {
		//退出聊天页面之前，清空页面传入的监听器
		let imService = getApp().globalData.imService;
		if (imService) {
			imService.onNewPrivateMessageReceive = (friendId, message) => {};
		}
	},
	methods: {
		async init(options) {
			let that = this;
			let imService = getApp().globalData.imService;
			that.currentUser = uni.getStorageSync('currentUser');
			//聊天对象
			let friendId = options.to;
			console.log("获取到的 friendId 为 " + friendId);
			//从服务器获取最新的好友信息
			that.friend = await restApi.findUserById(friendId);
			console.log('onLoad friend - ', JSON.stringify(that.friend));
			uni.setNavigationBarTitle({
				title: that.friend.name
			});
			that.messages = imService.getPrivateMessages(friendId);
			//监听新消息
			imService.onNewPrivateMessageReceive = (friendId, message) => {
				if (friendId === that.friend.uuid) {
					//聊天时，收到消息标记为已读
					that.markPrivateMessageAsRead(friendId);
					//收到新消息，是滚动到最底部
					that.scrollToBottom();
				}
			};
			//每次进入聊天页面，总是滚动到底部
			that.scrollToBottom();
			//收到的消息设置为已读
			if (that.messages.length !== 0) {
				that.markPrivateMessageAsRead(friendId);
			}
		},

		//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
		//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
		renderMessageDate(message, index) {
			if (index === 0) {
				return this.formatDate(message.timestamp);
			} else {
				if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
					return this.formatDate(message.timestamp);
				}
			}
			return '';
		},

		sendMessage(message) {
			let toId = message.to.id;
			let imService = getApp().globalData.imService;
			let localHistory = imService.getPrivateMessages(toId);
			localHistory.push(message);
			this.goEasy.im.sendMessage({
				message: message,
				onSuccess: function(message) {
					console.log('发送成功.', message);
				},
				onFailed: function(error) {
					console.log('发送失败:', error);
				}
			});
		},
		sendTextMessage() {
			//发送消息
			if (this.content.trim() !== '') {
				let body = this.content;
				if (this.content.length >= 50) {
					body = this.content.substring(0, 30) + '...';
				}
				let textMessage = this.goEasy.im.createTextMessage({
					text: this.content,
					to: {
						id: this.friend.uuid,
						type: this.GoEasy.IM_SCENE.PRIVATE,
						data: {
							name: this.friend.name,
							avatar: this.friend.avatar
						}
					},
					notification: {
						title: this.currentUser.name + '发来一段文字',
						body: body
					}
				});
				this.sendMessage(textMessage);
			}
			this.scrollToBottom();
			this.content = '';
		},
		loadMoreHistoryMessage() {
			//历史消息
			let self = this;
			let lastMessageTimeStamp = Date.now();
			let lastMessage = this.messages[0];
			if (lastMessage) {
				lastMessageTimeStamp = lastMessage.timestamp;
			}
			let currentLength = this.messages.length;
			this.goEasy.im.history({
				userId: self.friend.uuid,
				lastTimestamp: lastMessageTimeStamp,
				onSuccess: function(result) {
					//获取本地记录
					let imService = getApp().globalData.imService;
					let localHistory = imService.getPrivateMessages(self.friend.uuid);
					//添加加载的记录到本地记录尾部
					let messages = result.content;
					for (let i = messages.length - 1; i >= 0; i--) {
						localHistory.unshift(messages[i]);
					}
					if (localHistory.length === currentLength) {
						self.allHistoryLoaded = true;
					}
					self.messages = localHistory;
					uni.stopPullDownRefresh();
				},
				onFailed: function(error) {
					//获取失败
					if (error.code === 401) {
						console.log('获取历史消息失败,默认不开通，付费应用，可以在我的应用->查看详情，高级功能里自助开通');
					} else {
						console.log('获取历史消息失败, code:' + error.code + ',错误信息:' + error.content);
					}
					uni.stopPullDownRefresh();
				}
			});
		},
		scrollToBottom() {
			this.$nextTick(function() {
				uni.pageScrollTo({
					scrollTop: 2000000,
					duration: 10
				});
			});
		},
		markPrivateMessageAsRead(friendId) {
			this.goEasy.im.markPrivateMessageAsRead({
				userId: friendId,
				onSuccess: function() {
					console.log('标记为已读成功');
				},
				onFailed: function(error) {
					console.log(error);
				}
			});
		}
	}
};
</script>

<style lang="less">
@import './privateChat.css';
</style>
